package com.example.phone.cart;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.PtrHandler;
import com.example.phone.R;
import com.example.phone.base.BaseFragment;
import com.example.phone.base.MyApp;
import com.example.phone.base.RequestInterface;
import com.example.phone.base.ServerResponse;
import com.example.phone.bean.Cart;
import com.example.phone.bean.ShoppingCart;
import com.example.phone.bean.ShoppingCartList;
import com.example.phone.bean.User;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class CartFragment extends BaseFragment implements CartListAdapter.OnCartVisibilityChangeListener, CartListAdapter.OnCartTotalPriceChangeListener {
    @BindView(R.id.cart_view)
    RecyclerView cartView;
    @BindView(R.id.ll_no_order)
    LinearLayout llNoOrder;
    Unbinder unbinder;
    @BindView(R.id.price_total)
    TextView priceTotal;
    @BindView(R.id.order_view)
    LinearLayout orderView;
    @BindView(R.id.btn_order)
    TextView btnOrder;
    @BindView(R.id.list_fresh_layout)
    PtrClassicFrameLayout listFreshLayout;
    @BindView(R.id.floatingActionButton)
    FloatingActionButton floatingActionButton;


    private RecyclerView recyclerView;
    private CartListAdapter mCartListAdapter;
    private List<Cart> mShoppingCartList = new ArrayList<>();
    private MyApp app;

    @Override
    protected void initView() {
        app = (MyApp) getActivity().getApplication();

        //User user = app.getUser();


        unbinder = ButterKnife.bind(this, getmContentView());
        onVisibilityChange(true);

        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getShoppingCartList();
            }
        });

        listFreshLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                if (!cartView.canScrollVertically(-1)) {
                    return true;
                } else {
                    return false;
                }
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getShoppingCartList();
                frame.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        listFreshLayout.refreshComplete();
                    }
                }, 1800);
            }
        });

        mCartListAdapter = new CartListAdapter(getActivity(), mShoppingCartList);
        mCartListAdapter.setOnCartVisibilityChangeListener(this);
        mCartListAdapter.setOnCartTotalPriceChangeListener(this);

        recyclerView = getmContentView().findViewById(R.id.cart_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        recyclerView.setAdapter(mCartListAdapter);


    }

    @Override
    protected void initData() {
        getShoppingCartList();
    }

    @Override
    protected void init() {

    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_cart;
    }

    private void getShoppingCartList() {
        log("send request");

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface.CartRequest cartRequest = retrofit.create(RequestInterface.CartRequest.class);
        Call<ServerResponse<ShoppingCartList>> call = cartRequest.getShoppingCartList(app.getUser().getId());
        call.enqueue(new Callback<ServerResponse<ShoppingCartList>>() {

            @Override
            public void onResponse(Call<ServerResponse<ShoppingCartList>> call, Response<ServerResponse<ShoppingCartList>> response) {
                if (response.body().getStatus() == 0) {
                    log("success");
                    ShoppingCartList shoppingCartList = response.body().getData();
                    if (shoppingCartList != null) {
                        List<Cart> list = shoppingCartList.getCartProductVoList();
                        if (list != null && list.size() > 0) {
                            mShoppingCartList.clear();
                            mShoppingCartList.addAll(list);

                            int count = 0;
                            for (Cart s : mShoppingCartList) {
                                count += s.getQuantity();
                            }

                            onTotalPriceChange(shoppingCartList.getCartTotalPrice(), count);
                            mCartListAdapter.notifyDataSetChanged();
                            onVisibilityChange(true);

                        } else {
                            onVisibilityChange(false);
                        }
                    } else {
                        toastShort("Error: List is empty!");
                        onVisibilityChange(false);
                    }
                } else {
                    toastShort("购物车加载失败，请检查网络");
                    onVisibilityChange(false);
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<ShoppingCartList>> call, Throwable t) {
                toastShort("购物车加载失败，请检查网络");
                onVisibilityChange(false);
            }
        });
    }


    public void onVisibilityChange(boolean visible) {
        if (visible) {
            llNoOrder.setVisibility(View.GONE);
            orderView.setVisibility(View.VISIBLE);
            listFreshLayout.setVisibility(View.VISIBLE);
        } else {
            llNoOrder.setVisibility(View.VISIBLE);
            orderView.setVisibility(View.GONE);
            listFreshLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void onTotalPriceChange(double totalPrice, int count) {
        priceTotal.setText(getString(R.string.rmb_price_total, totalPrice));
        btnOrder.setText(getString(R.string.product_item_count, count));
    }


}
